package threadPool.task;

/**
 * 异步线程回调任务
 * @author jinmiao
 * 2014-9-12 上午10:58:57
 */
public abstract class DisruptorAsyncBackTask extends LocalTask
{

	private volatile boolean isAsyncOver;

    protected Throwable e;



    public void execute(){
        long start = System.currentTimeMillis();
        //执行异步
        if(!isAsyncOver)
        {
            try {
                async();
            } catch (Throwable e) {
               this.e= e;
                //e.printStackTrace();
                if (logger.isErrorEnabled()) {
                    logger.error("Error", "#.DisruptorAsyncTask.execute", "param",e);
                }
            }
            isAsyncOver = true;
            super.messageExecutor.execute(this);
            long useTime = System.currentTimeMillis()-start;
            if(useTime>1)
            {
                logger.error("异步回调耗时"+getClass().getName()+" "+ useTime);
            }
            return;
        }
        //执行回调
        try {
            if(e ==null)
                doCallBack();
            else
                onFail(e);
        } catch (Throwable e) {
            if (logger.isErrorEnabled()) {
                logger.error("Error", "#.DisruptorAsyncBackTask.execute", "param", e);
            }
        }
        long useTime = System.currentTimeMillis()-start;
        if(useTime>1)
        {
            logger.error("异步回调耗时"+getClass().getName()+" "+ useTime);
        }
    }

    /**
     * 异步调用
     */
    protected abstract void async() throws Exception;

	protected abstract void onFail(Throwable e);

	/**
	 * 异步处理完后回原线程做处理
	 */
	protected abstract void doCallBack();

}
